<template>
  <div class="user-edit-container">
    <van-nav-bar
      title="编辑资料"
      @click-left="$router.back()"
      left-arrow
      fixed
    />
    <!-- 用户资料 -->
    <van-cell-group class="action-card">
      <van-cell title="头像" is-link center>
        <template #default>
          <van-image
            round
            class="avatar"
            :src="userProfile.photo"
            @click="$refs.fileRef.click()"
          />
          <!-- 文件选择框 -->
          <!-- accept 可以用来指定选择文件的类型 -->
          <input
            type="file"
            accept="image/*"
            @change="onFileChange"
            v-show="false"
            ref="fileRef"
          />
        </template>
      </van-cell>
      <van-cell
        title="名称"
        is-link
        :value="userProfile.name"
        @click="onNameCellClick"
      />
      <van-cell
        title="生日"
        is-link
        :value="userProfile.birthday"
        @click="onBirthCellClick"
      />
    </van-cell-group>

    <van-dialog
      v-model="showNameDialog"
      title="修改名称"
      show-cancel-button
      :before-close="beforeClose"
    >
      <van-field
        autofocus
        class="input_b"
        v-model="name"
        placeholder="请输入修改名称"
        input-align="center"
        border
        ref="nameRef"
      />
    </van-dialog>
    <van-action-sheet v-model="showBirthSheet">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthSheet = false"
        @confirm="onConfirm"
      />
    </van-action-sheet>
  </div>
</template>

<script>
import {
  getUserProfileAPI,
  updataAvatorAPI,
  updataUserProfileAPI
} from '@/api/userAPI.js'
import dayjs from 'dayjs'
export default {
  name: 'UserEdit',
  data() {
    return {
      userProfile: {},
      showNameDialog: false,
      name: '',
      showBirthSheet: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2030, 10, 1),
      currentDate: new Date(2021, 0, 17)
    }
  },

  components: {},

  computed: {},

  mounted() {
    this.getUserProfile()
  },

  methods: {
    async getUserProfile() {
      const { data: res } = await getUserProfileAPI()
      this.userProfile = res.data
    },
    async onFileChange(e) {
      const files = e.currentTarget.files
      if (files.length === 0) return
      // 获取用户选择的头像
      const img = files[0]
      const fd = new FormData()
      fd.append('photo', img)
      const { data: res } = await updataAvatorAPI(fd)
      if (res.message === 'OK') {
        this.getUserProfile()
        this.$notify({
          type: 'success',
          message: '更新头像成功',
          duration: 2000
        })
      }
    },
    onNameCellClick() {
      this.name = this.userProfile.name
      this.showNameDialog = true
      this.$nextTick(() => {
        this.$refs.nameRef.focus()
      })
    },
    beforeClose(action, done) {
      if (action === 'cancel') return done()
      // 判断输入的名字的长度
      if (this.name === '' || this.name.length > 8) {
        done(false)
        this.$notify({
          type: 'warning',
          message: '名字的长度在1-8',
          duration: 2000
        })
        this.$refs.nameRef.focus()
        return
      }

      // 发请求提交数据
      this.updataName(done)
    },
    async updataName(done) {
      try {
        const { data: res } = await updataUserProfileAPI({ name: this.name })
        if (res.message === 'OK') {
          done()
          this.getUserProfile()
          this.$notify({
            type: 'success',
            message: '名称修改成功',
            duration: 2000
          })
        }
      } catch (error) {
        done()
        this.$notify({
          type: 'danger',
          message: '名称修改失败',
          duration: 2000
        })
      }
    },
    onBirthCellClick() {
      this.showBirthSheet = true
      if (this.userProfile.birthday) {
        this.currentDate = new Date(this.userProfile.birthday)
      } else {
        this.currentDate = new Date()
      }
    },
    async onConfirm(value) {
      this.showBirthSheet = false
      const dateStr = dayjs(value).format('YYYY-MM-DD')
      const { data: res } = await updataUserProfileAPI({ birthday: dateStr })
      if (res.message === 'OK') {
        this.getUserProfile()
        this.$notify({ type: 'success', message: '更新成功', duration: 2000 })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.user-edit-container {
  padding-top: 92px;
  .avatar {
    width: 100px;
    height: 100px;
  }
}
.input_b /deep/ .van-field__control {
  border: 1px solid #999;
}
</style>
